<template>
<view class="page"> 
	<view class="body"> 
		<!-- 已登录绑定账号 -->
		<template v-if="type=='bind'">
			<view class="form-wrap">
				<view class="bind-icon-bar">
					<view class="icon wx-icon"><image src="@/static/images/58x58.png" mode="widthFix"></image></view>
					<view class="icon bind-icon"><image src="@/static/images/bind_icon.png" mode="widthFix"></image></view>
					<view class="icon login-icon"><image src="@/static/images/wechat.png" mode="widthFix"></image></view>
				</view>
				<view class="phone-login">
					<view class="account-phone">
						<text class="label">绑定账号：</text>
						<text class="phone">{{replace_phone}}</text>
					</view> 
					<view class="login-btn active" @click="bindPhone">微信授权绑定账号</view>  
				</view>				 
			</view>
		</template>
		
		<!-- 未登录绑定手机号 -->
		<template v-if="type=='auth'">
			<view class="form-wrap">
				<view class="bind-icon-bar">
					<view class="icon wx-icon"><image src="@/static/images/58x58.png" mode="widthFix"></image></view>
					<view class="icon bind-icon"><image src="@/static/images/bind_icon.png" mode="widthFix"></image></view>
					<view v-if="wx_info.openId" class="icon login-icon"><image :src="wx_info.avatarUrl" mode="widthFix"></image></view>
					<view v-else-if="iphone_info.openId" class="icon iphone-icon"><image src="@/static/images/iphone_icon.png" mode="widthFix"></image></view>
				</view>
				<view class="phone-login"> 
					<view class="item">
						<view class="label iconfont f-s46">&#xe607;</view>
						<input type="number" v-model="phone" maxlength="11" :focus="phoneFocus" class="phone-inp" placeholder="请输入手机号" />
						<view v-if="phone" class="iconfont f-s28" @click="clearPhone">&#xe8bb;</view>
					</view>
					<view class="item"> 
						<view class="label iconfont f-s40">&#xe625;</view>
						<input type="number" v-model="phoneCode" :focus="codeFocus" class="code-inp" placeholder="请输入验证码" />
						<view class="get-code" @click="sendSms">{{count_time_text}}</view> 
					</view>
					<view class="login-btn active" @click="bindPhoneAuth">立即绑定</view> 
					<!-- <view class="hr-line">或者</view> 
					<button open-type="getPhoneNumber" class="bind-wx-phone" @getphonenumber="GetPhoneNumber">快速绑定微信手机号</button> -->
					<!-- <button open-type="getPhoneNumber" @bindgetphonenumber="GetPhoneNumber">快速绑定微信手机号</button> -->
				</view>				 
			</view>
		</template>
		
		<!-- 解除绑定 -->
		<template v-if="type=='upbind'">
			<view class="form-wrap">
				<view class="bind-icon-bar">
					<view class="icon wx-icon"><image src="@/static/images/58x58.png" mode="widthFix"></image></view>
					<view class="icon bind-icon"><image src="@/static/images/upbind.png" mode="widthFix"></image></view>
					<view class="icon login-icon"><image :src="wx_info.avatarUrl" mode="widthFix"></image></view>					
				</view>
				<view class="phone-login">
					<view class="account-phone">
						<text class="label">绑定账号：</text>
						<text class="phone">{{replace_phone}}</text>
					</view> 
					<view class="login-btn active" @click="upBindWechat">解除绑定</view> 					 
				</view>				 
			</view>
		</template>
	</view> 
</view>
</template>

<script>
import {checkPhone,getCurrenPage,replaceStr} from '@/common/util.js'
import {getUserInfo} from '@/common/login.js' 
import Timer from '@/common/timer.js'
import {
		HTTP_REQUEST_URL
	} from '@/config.js'
export default{
	name:'demo',
	data(){
		return{
			userInfo:uni.getStorageSync('userInfo'),
			type:'bind',    // auth 授权登录  bind 授权绑定   upbind 解除绑定 
			phone:'',
			phoneCode:'', 
			backType:'',                          // next : 下一级页面  prev : 返回上级页面
			backurl:'',
			jsCode:'',
			openId:'',
			wm_id:'',  
			phone_code_type:"4",  
			replace_phone:"",
			count_time_text: '获取验证码',
			isStop:true,
			phoneFocus:false,
			codeFocus:false,
			isSendCode:true,
			isStopBind:true, 
			timer:null,
			wx_info:{},
			iphone_info:{}
		}
	},
	onShow() {
		
	},
	async onLoad(params) { 
		console.log(params)
		this.type=params.type;
		this.backType=params.backType;
		this.backurl=params.backurl;
		this.openId=params.openid;  		
		
		if(this.type=='auth'){ 
			if(params.wxInfo){
				this.wx_info=JSON.parse(params.wxInfo);
				uni.setNavigationBarTitle({
					title:'微信绑定账号'
				})
			}
			if(params.iphoneInfo){
				this.iphone_info=JSON.parse(params.iphoneInfo);
				console.log(this.iphone_info)
				uni.setNavigationBarTitle({
					title:'苹果绑定账号'
				})
			}
			
		}else if(this.type=='bind'){
			this.replace_phone = replaceStr(this.userInfo.phone, 3, '****'); 
			uni.setNavigationBarTitle({
				title:'账号绑定微信'
			})
		}else if(this.type=='upbind'){
			this.replace_phone = replaceStr(this.userInfo.phone, 3, '****'); 
			uni.setNavigationBarTitle({
				title:'解除微信绑定'
			}) 
			 
			if(this.userInfo.wx_info){
				this.wx_info=JSON.parse(this.userInfo.wx_info);  
			}				 
		}
		
	},
	onUnload() {
		if (this.timer) {
			this.timer.stop();
		}
	},
	onHide() {
		if (this.timer) {
			this.timer.stop();
		}
	},
	methods:{
		
		// 授权绑定已登录账号
		bindPhone:function(){
			let _this=this;
			uni.login({
			 	provider: 'weixin', 
			    success: function (loginRes) { 
					uni.getUserInfo({
						provider: 'weixin',
						success:async function (infoRes) {     
							infoRes.userInfo.nickName=''; 
							
							let res=await _this.$api.user_api.updatePwd({
								wx_info:JSON.stringify(infoRes.userInfo),
								openid:infoRes.userInfo.openId
							})
							uni.showLoading({
								mask:true,
								title:'账号绑定中...'
							})
							if(res.data.ret==0){								
								uni.showToast({
									icon:'success',
									title:'账号绑定成功',
									mask:true,
									duration:1000,
									success() {
										setTimeout(()=>{
											uni.hideLoading();
											uni.navigateBack({
												delta:1
											})		
											let userInfo_update=uni.getStorageSync('userInfo');
											userInfo_update.wx_info=JSON.stringify(infoRes.userInfo);
											uni.setStorage({
												key:"userInfo",
												data:userInfo_update
											});
											_this.$store.commit("UPDATE_USERINFO",1);     // 绑定成功 更新上页 userinfo
										},300)
									}
								})
							}else{
								uni.hideLoading(); 
								uni.showToast({
									icon:'error',
									title:res.data.message,
									mask:true,
									duration:1000,
									success() {
										 
									}
								})
							}
						}
					});
			    }
			})
		},
		
		//发送验证码
		sendSms: async function() { 
			// 1 找回密码  2 重置密码  3 手机登录  空/0 密码登录 4 登录注册  5 微信授权绑定账号 
			let _this = this; 
			let cookie=[];
			//#ifdef APP-PLUS
			 if(plus.os.name === "iOS"){
				cookie=null;
			}
			//#endif
			this.phone_code = "";
			
			if(!this.isSendCode) return; 
			
			if(this.phone_code_type==4){
				if (this.phone == '') {
					uni.showToast({
						icon: "none",
						title: "请输入手机号",
						mask: true
					})
					return
				}
				if (!checkPhone(this.phone)) {
					uni.showToast({
						icon: "none",
						title: "请输入正确手机号",
						mask: true
					})
					return
				}
				if (this.isSendCode) {
					this.isSendCode = false;					
					
					uni.request({
						url: HTTP_REQUEST_URL + '/user/sendsms',
						method: 'POST',
						data: {
							tel: _this.phone,
							type: _this.phone_code_type
						},
						dataType: 'json',
						timeout: 30000,
						header: {
							"Content-Type": "application/x-www-form-urlencoded",
							'Cookie': cookie
						}, 
						success: (res) => { 
							
							if (res.data.ret == 0) {
								uni.hideLoading();
								uni.showToast({
									icon: "success",
									title: "验证码发送成功",
									mask: true
								})
								this.timer = new Timer({
									type: '1',
									num: 60
								});
				
								this.timer.start({
									success: function(res) {
										_this.count_time_text = res + 's';
									},
									complate: function() {
										_this.count_time_text = '获取验证码';
										setTimeout(() => {
											_this.isSentCode = true;
										}, 300)
									}
								}) 
								uni.setStorage({
									'key': 'cookiekey',
									'data': res.header['Set-Cookie']
								}) 
							} else {
								uni.showToast({
									icon: "none",
									image: "../../static/images/error.png",
									title: res.data.message,
									mask: true
								})
								setTimeout(() => {
									_this.count_time_text = '获取验证码';
									_this.isSendCode = true;
								}, 300)
							}
						},
						fail: (err) => {
				
						}
					})					 
				
				}
			}
			 
		
		},
		
		// 授权登录绑定账号
		bindPhoneAuth:async function(){
			let _this=this;
			if (this.phone == '') {
				uni.showToast({
					icon: "none",
					title: "请输入手机号",
					mask: true
				})
				return
			}else if (this.phoneCode == '') {
				uni.showToast({
					icon: "none",
					title: "请输入验证码",
					mask: true
				})
				return
			} else {
				if (this.isStop) {
					this.isStop = false;
					uni.showLoading({
						mask: true,
						title: '账号绑定中...'
					}) 
					let res = await this.$api.user_api.checksms({
						code: this.phoneCode,
						type: this.phone_code_type
					})  
					if (res.data.ret == 0) {		
						// 绑定微信
						if(this.wx_info.openId){
							let bind_res=await _this.$api.user_api.updatePwd({
								wx_info:JSON.stringify(this.wx_info),
								openid:this.wx_info.openId 
							}) 
							console.log(res.data.data)
							if(bind_res.data.ret==0){
								uni.hideLoading();
								uni.showToast({
									icon: "success",
									title: "绑定成功",
									mask: true,
									duration: 1000,
									async success() {
										let save_cookie = await _this.$api.user_api.saveCookie();
										_this.userInfo = res.data.data;									
										_this.$store.commit('UPDATE_LOGIN_STATUS',true);									
										uni.setStorage({
											key: 'userInfo',
											data: _this.userInfo
										})
										
										setTimeout(() => {
											uni.switchTab({
												url:'/pages/index/index'
											})
											_this.isStop = true;
										}, 1000)
									}
								})
							}else{
								uni.hideLoading();
								uni.showToast({
									icon: "error",
									title: "绑定失败",
									mask: true,
									duration: 1000,
									async success() {									 
										setTimeout(() => {
											uni.navigateBack({
												delta:1
											})										 
										}, 1000)
									}
								})
								
							}
						}
						
						// 绑定苹果
						if(this.iphone_info.openId){
							let bind_res=await _this.$api.user_api.bindIphone({								
								pg_openid:this.iphone_info.openId 
							})  
							if(bind_res.data.ret==0){
								uni.hideLoading();
								uni.showToast({
									icon: "success",
									title: "绑定成功",
									mask: true,
									duration: 1000,
									async success() {
										let save_cookie = await _this.$api.user_api.saveCookie();
										_this.userInfo = res.data.data;									
										_this.$store.commit('UPDATE_LOGIN_STATUS',true);									
										uni.setStorage({
											key: 'userInfo',
											data: _this.userInfo
										})
										
										setTimeout(() => {
											uni.switchTab({
												url:'/pages/index/index'
											})
											_this.isStop = true;
										}, 1000)
									}
								})
							}else{
								uni.hideLoading();
								uni.showToast({
									icon: "error",
									title: "绑定失败",
									mask: true,
									duration: 1000,
									async success() {									 
										setTimeout(() => {
											uni.navigateBack({
												delta:1
											})										 
										}, 1000)
									}
								})
								
							}
						}
						
					
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: "none",
							image: "../../static/images/error.png",
							title: res.data.message,
							mask: true
						})
						setTimeout(() => {
							_this.isStop = true;
						}, 300)
					}
				}
			}
					
		},
		
		// 解除微信绑定
		upBindWechat:function(){
			let _this=this;
			uni.showModal({
				content:'确定要解除账号与微信的绑定吗?',
				mask:true,
				confirmText:'解除绑定',
				cancelText:'暂不解绑',
				async success(res) {
					if(res.confirm){
						let res=await _this.$api.user_api.updatePwd({
							wx_info:''
						})
						uni.showLoading({
							mask:true,
							title:'解除绑定中...'
						})
						if(res.data.ret==0){
							uni.hideLoading();
							uni.showToast({
								icon:'success',
								title:'账号解绑成功',
								mask:true,
								duration:1000,
								success() {
									setTimeout(()=>{
										uni.navigateBack({
											delta:1
										})
										_this.$store.commit("UPDATE_USERINFO",1);     // 绑定成功 更新上页 userinfo
									},300)
								}
							})
						}else{
							uni.hideLoading();
							uni.showToast({
								icon:'error',
								title:'账号解绑失败',
								mask:true,
								duration:1000,
								success() {
									 
								}
							})
						}
					}
				}
				
			})
		},
		 
		 
		// 绑定微信手机号
		GetPhoneNumber:async function(e){ 
			let _this=this;   
			console.log(e)
			
			return
			let res=await this.$api.user_api.bindWxPhone({
				wm_id:this.wm_id,
				iv:e.detail.iv,
				code:this.jsCode, 
				encryptedData:e.detail.encryptedData,
				invite_code:this.invite_code,
				type:1    // 若已绑定其他微信，强制下线
			})  
			if(res.data.code==200){
				let token=res.data.data.token;
				uni.showToast({
					icon:"success", 
					title:'绑定成功',
					mask:true,
					duration:1000,
					async success() {
						setTimeout(()=>{
							_this.isStopBind=true;
							if(_this.backType=='prev'){
								let prevPage=getCurrenPage(2);
								prevPage.$vm.loginStateUpdate=true;
								uni.navigateBack({
									delta:1
								})
							}else if(_this.backType=='next'){
								if(_this.backurl){
									uni.redirectTo({
										url:_this.backurl
									})
								} 
							}else{
								uni.redirectTo({
									url:'/pages/index/index'
								})
							}
							
						},1000)						 
						
						// _this.$store.commit('login',token); 
						let userInfo=await getUserInfo(token);
						uni.setStorage({
							key:'userInfo',
							data:userInfo
						});
						uni.setStorage({
							key:'token',
							data:token
						});
					}
				})
			}else{
				uni.showToast({
					icon:"none",
					image:"../../static/images/error.png",
					title:res.data.msg,
					mask:true,
					duration:2000
				})
			} 
			
		},
		
		clearPhone:function(){
			this.phone='';
		}
		
	},
	onUnload() {
		if(this.timer){
			this.timer.stop()
		}
		
	},
	computed:{
		
	},
	components:{
		
	}
}
</script>

<style lang="less">
.page,page{background: #FFFFFF}

.account-phone{
	display: flex;
	font-size: 16px;
}

.form-wrap{
	width:80%;
	margin:0 auto;
}

.bind-icon-bar{
	display: flex;
	justify-content: center;
	margin:80rpx 0 40rpx;
	.icon{
		width:80rpx;
		height:80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin:0 20rpx;
	}
	.wx-icon image{
		width:100%;
		border-radius: 10rpx;
	}
	.iphone-icon image{
		width:100%;
		border-radius: 10rpx;
	}
	.bind-icon image{
		width:70%
	}
	.login-icon image{
		width:100%;
		border-radius: 10rpx; 
	}
}  

.phone-login{
	margin:100rpx 0 150rpx;
	.item{
		display: flex;
		padding:0 20rpx;
		border-bottom:2rpx solid #ddd; 
		margin-bottom: 30rpx;
	}
} 
.phone-login .item .label,
.phone-login .item .get-code{
	width:80rpx;
	height:90rpx;
	text-align: right;
	line-height: 90rpx;
	color:#999;
	font-size:28rpx;
}
.phone-login .item .get-code{
	color:#09f;
}
.phone-login .item .phone-inp{
	flex-grow: 2;
	height:60rpx;  
	margin-top:15rpx; 
	font-size:28rpx;
}
.phone-login .item .get-code{
	width:250rpx;
}
.phone-login .item .get-code.active{
	color:#666;
}
.phone-login .item .code-inp{
	flex-grow: 2;
	height:60rpx;   
	margin-top:15rpx;
	max-width: 40%;
	font-size:28rpx;
}
.phone-login .item .iconfont{
	width: 80rpx;
	line-height: 90rpx;
	text-align: center;
	color:#ccc;
	font-size:40rpx;
}
.phone-login .login-btn{
	height:90rpx;
	text-align: center;
	line-height: 90rpx;
	margin-top:50rpx;
	background: #ccc;
	border-radius: 50rpx;
	font-size: 30rpx;
	color:#fff;
}
.phone-login .login-btn.active{
	background: #f00;
	color:#fff;
}
.hr-line{
	position:relative;
	text-align: center;
	margin-top:20rpx;
	font-size: 28rpx;
	color:#999;
}
.bind-wx-phone{
	height: 90rpx;
	text-align: center;
	line-height: 90rpx;
	margin-top: 20rpx;
	background: #07c160;
	border-radius: 50rpx;
	font-size: 30rpx;
	color: #fff;
}
</style>
